<?php
namespace app\model;

use think\Model;
use app\model\BookType;
use think\helper\Str;

class Book extends Model
{
    protected $table = "ea_book";

    /**
     * [setWhere description]
     * @since  2022-04-22
     * @author Dai哥
     * @param  array      $data [description]
     * @return [type]           [description]
     */
    public static function setWhere($data)
    {
        $model = self::whereNull('delete_time')->where('status', 1)->order('create_time DESC');

        if(isset($data['pre_id']) && $data['pre_id'] !== ''){
            $model = $model->where('pre_id', $data['pre_id']);
        }

        if(isset($data['som_id']) && $data['som_id'] !== ''){
            $model = $model->where('som_id', $data['som_id']);
        }

        if(isset($data['page']) && isset($data['limit'])){

            $data['limit'] = $data['limit'] > 20 ? 10 : $data['limit'];

            $model = $model->page($data['page'], $data['limit']);
        }

        return $model;
    }

    /**
     * [getBookTypeList 获取book列表]
     * @since  2022-04-22
     * @author Dai哥
     * @param  [type]     $data [description]
     * @return [type]           [description]
     */
    public static function getBookList($data)
    {
        $list = self::setWhere($data)
            ->field('id, title, pre_id, som_id, downloads_num, suffix, yulan, create_time, size')
            ->with(['pre', 'som'])
            ->select();

        return $list;
    }

    public function pre()
    {
        return $this->hasOne(BookType::class, 'id', 'pre_id')->field('id, name');
    }

    public function som()
    {
        return $this->hasOne(BookType::class, 'id', 'som_id')->field('id, name');
    }



    public function getSuffixAttr($value)
    {
        $str = '';

        switch ($value) {
            case 'doc':
                $str = 'docx';
                break;
            
            case 'docx':
                $str = 'docx';
                break;
            
            case 'zip':
                $str = 'zip';
                break;
            
            case 'pdf':
                $str = 'pdf';
                break;
            
            case 'xls':
                $str = 'excel';
                break;
            
            case 'xlsx':
                $str = 'excel';
                break;
            
            default:
                $str = 'text';
                break;
        }

        return $str;
    }

    public function getCreateTimeAttr($value)
    {
        return get_friend_date($value);
    }

    public function getImgAttr($value)
    {
        if($value && Str::contains($value, 'http')){
            return $value;
        }

        return '';
    }
}